package com.app.utils;

import java.io.File;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.TypedArray;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

public class SystemHelper {

	public static void closeInputFromWindow(Activity activity) {
		View view = activity.getWindow().peekDecorView();
		if (view != null) {
			InputMethodManager inputmanger = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	private static int SCREEN_WIDTH = -1;

	public static int getScreenWidth(Context context) {
		if (SCREEN_WIDTH < 0) {
			WindowManager wm = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			DisplayMetrics outMetrics = new DisplayMetrics();
			Display display = wm.getDefaultDisplay();
			display.getMetrics(outMetrics);
			SCREEN_WIDTH = outMetrics.widthPixels;
		}
		return SCREEN_WIDTH;
	}

	public static float getActionBarHeight(Context context) {
		TypedArray actionbarSizeTypedArray = context
				.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
		float h = actionbarSizeTypedArray.getDimension(0, 0);
		return h;
	}

	/**
	 * 获取当前Android系统的Api版本
	 * 
	 * @return
	 */
	public static int getCurrentSdk() {
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		return currentapiVersion;
	}

	public static String getVersion() {
		return android.os.Build.VERSION.RELEASE;
	}

	public static String getVersionName(Context context) {
		String version = null;
		try {
			PackageManager packageManager = context.getPackageManager();
			// getPackageName()是你当前类的包名，0代表是获取版本信息
			PackageInfo packInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			version = packInfo.versionName;
		} catch (NameNotFoundException e) {
			return null;
		}
		return version;
	}

	/**
	 * 获取手机串号（IMEI）
	 * <p>
	 * 权限要求 android.permission.READ_PHONE_STATE
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceImei(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();
		// 获取电话号码，但是并不靠谱。。慎用!!!!!
		// String tel = tm.getLine1Number();
		return imei;
	}

	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			PackageManager packageManager = context.getPackageManager();
			// getPackageName()是你当前类的包名，0代表是获取版本信息
			PackageInfo packInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			versionCode = packInfo.versionCode;
		} catch (NameNotFoundException e) {
			return 0;
		}
		return versionCode;
	}

	/**
	 * 获取手机型号
	 * <p>
	 * 权限要求 android.permission.READ_PHONE_STATE
	 * 
	 * @return
	 */
	public static String getMobile() {
		return android.os.Build.MODEL;
	}

	/** 获取手机名称 */
	public static String getManufacturer() {
		return android.os.Build.MANUFACTURER;
	}

	/**
	 * 获取手机mac地址<br/>
	 * 错误返回12个0
	 */
	public static String getMacAddress(Context context) {
		// 获取mac地址：
		String macAddress = "00:00:00:00:00:00";
		try {
			WifiManager wifiMgr = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = (null == wifiMgr ? null : wifiMgr
					.getConnectionInfo());
			if (null != info) {
				if (!TextUtils.isEmpty(info.getMacAddress()))
					macAddress = info.getMacAddress();
				else
					return macAddress;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return macAddress;
		}
		return macAddress;
	}

	public static File createFile(String path) {
		File file = new File(path);
		// 寻找父目录是否存在
		File parent = new File(file.getAbsolutePath().substring(0,
				file.getAbsolutePath().lastIndexOf(File.separator)));
		// 如果父目录不存在，则递归寻找更上一层目录
		if (!parent.exists()) {
			createFile(parent.getPath());
			// 创建父目录
			parent.mkdirs();
		}
		return file;
	}

	public static String getCurrentNetType(Context context) {
		String type = "";
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		if (info == null) {
			type = "null";
		} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
			type = "WIFI";
		} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
			int subType = info.getSubtype();
			if (subType == TelephonyManager.NETWORK_TYPE_CDMA
					|| subType == TelephonyManager.NETWORK_TYPE_GPRS
					|| subType == TelephonyManager.NETWORK_TYPE_EDGE) {
				type = "2G";
			} else if (subType == TelephonyManager.NETWORK_TYPE_UMTS
					|| subType == TelephonyManager.NETWORK_TYPE_HSDPA
					|| subType == TelephonyManager.NETWORK_TYPE_EVDO_A
					|| subType == TelephonyManager.NETWORK_TYPE_EVDO_0
					|| subType == TelephonyManager.NETWORK_TYPE_EVDO_B) {
				type = "3G";
			} else if (subType == TelephonyManager.NETWORK_TYPE_LTE) {// LTE是3g到4g的过渡，是3.9G的全球标准
				type = "4G";
			}
		}
		return type;
	}

	/**
	 * 获取手机服务商信息
	 * 
	 * android.permission.READ_PHONE_STATE
	 * */
	 public String getProvidersName(Context context) {  
		 TelephonyManager telephonyManager  = (TelephonyManager) context  
	                .getSystemService(Context.TELEPHONY_SERVICE);  
	        String ProvidersName = null;  
	        // 返回唯一的用户ID;就是这张卡的编号神马的  
	        String IMSI = telephonyManager.getSubscriberId();  
	        // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。  
	        System.out.println(IMSI);  
	        if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {  
	            ProvidersName = "中国移动";  
	        } else if (IMSI.startsWith("46001")) {  
	            ProvidersName = "中国联通";  
	        } else if (IMSI.startsWith("46003")) {  
	            ProvidersName = "中国电信";  
	        }  
	        return ProvidersName;  
	    }  
	
	public static String getCurProcessName(Context context) {
		int pid = android.os.Process.myPid();
		ActivityManager mActivityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
				.getRunningAppProcesses()) {
			if (appProcess.pid == pid) {
				return appProcess.processName;
			}
		}
		return null;
	}
}
